﻿using System;
using System.Linq;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.TaskManager.Core.Infrastructure;
using ZilLion.TaskManager.Core.TaskRunTime.AppDomain;
using ZilLion.TaskManager.Core.TaskRunTime.Exe;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Entity;
using ZilLion.TaskManager.Repository;

namespace ZilLion.TaskManager.Core.Command
{
    /// <summary>
    ///     关闭任务命令
    /// </summary>
    [Serializable]
    public class StopTaskCommand : BaseCommand
    {
        private readonly TaskConfigRespository _taskConfigRespository = new TaskConfigRespository();
        private readonly TaskModuleConfigRespository _taskModuleRespository = new TaskModuleConfigRespository();

        public override void Execute()
        {
            TaskConfig taskConfig = null;
            var response = _taskConfigRespository.GetTaskConfigById(CommandInfo.Taskid);
            if (response != null && response.TaskConfigList != null)
                taskConfig = response.TaskConfigList.FirstOrDefault();
            if (taskConfig == null)
            {
                CustomTaskLogger.Print(Loglevel.Warn, $"{CommandInfo.Taskid}找不到对应CONFIG");
            }
            else
            {
                var taskModuleresponse = _taskModuleRespository.GetTaskModuleConfigById(taskConfig.TaskmoduleId);
                var taskModuleConfig = taskModuleresponse?.TaskModuleList?.FirstOrDefault();
                if (ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().TaskRuntimeType ==
                    TaskRuntimeType.Appdomain)
                {
                    TaskAppDomainExcuteProvider.GetInstance().PauseTask(taskConfig, taskModuleConfig);
                }
                else
                {
                    TaskExeRuntime.GetInstance().PauseTask(taskConfig);
                }
            }
        }
    }
}